package com.onelap.bls.tc.activity.index;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.widget.Button;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.blslib.eventbus.Event;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onelap.bls.tc.R;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothDialogHelper;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeParams;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeService;
import com.onelap.bls.tc.activity.bluetooth_le.BluetoothLeUtil;
import com.onelap.bls.tc.activity.entry.EntryActivity;
import com.onelap.bls.tc.config.Constant;
import com.onelap.bls.tc.utils.PermissionUtil;
import com.onelap.bls.tc.utils.TitleBar;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@SuppressLint("SetTextI18n")
public class IndexActivity extends BaseActivity implements BluetoothLeUtil.BluetoothUtilCallback {

    @BindView(R.id.rv_device_list)
    RecyclerView rvDeviceList;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.btn_connect)
    Button btnConnect;

    private List<DeviceBean> bluetoothDeviceList = new ArrayList<>();
    private DeviceListAdapter deviceListAdapter;
    private BluetoothAdapter bluetoothAdapter;
    private boolean searchDeviceState = false;  //搜索设备的状态，默认未搜索
    private int defaultSelectDevice = -1; //默认选中的设备
    //private BluetoothDevice selectBluetoothDevice = null;//选中的设备
    private BluetoothLeService bluetoothLeService;
    private DeviceBean selectDeviceBean = null;
    private BluetoothLeUtil bluetoothLeUtil;

    private boolean isOpenBluetoothLeService = false;
    private ProgressDialog progressDialog;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    public void onStickyEventBusCome(Event event) {
        super.onStickyEventBusCome(event);
        if (event.getCode() == 0) {
            bluetoothDeviceList.clear();
            bluetoothLeUtil.closeBleConnectDevice();
            deviceListAdapter.notifyDataSetChanged();
            bluetoothLeUtil.searchBluetoothDevice(bluetoothAdapter, true);
        }
    }

    @Override
    protected void initParams() {
        super.initParams();

        bluetoothLeUtil = new BluetoothLeUtil(this);

        bluetoothAdapter = bluetoothLeUtil.getBluetoothAdapter(getActivity());

        if (bluetoothAdapter == null) {
            BluetoothDialogHelper.showDialog(getActivity(), "提示", "当前设备不支持蓝牙", false, new BluetoothDialogHelper.DialogBtnCallback() {
                @Override
                public void dialogBtnCallback(int type) {
                    AppUtils.exitApp();
                }
            });
            return;
        }

        deviceListAdapter = new DeviceListAdapter(bluetoothDeviceList);

        bluetoothLeUtil.bindBluetoothService(getActivity(), BluetoothLeService.class, BluetoothLeParams.intentActions);

        PermissionUtil.applyForPermission(Constant.PERMISSION_LIST, false, new PermissionUtil.HasPermission() {
            @Override
            public void hasPermission() {
            }
        });
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_index;
    }

    @Override
    protected void initFvb() {
        super.initFvb();
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        TitleBar titleBar = findViewById(R.id.tb_title_bar);
        titleBar.setTitle("设备选择");
        titleBar.setBackgroundColor(Color.BLACK);
        titleBar.setTitleColor(Color.WHITE);
    }

    @Override
    protected void initView() {
        super.initView();
        rvDeviceList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvDeviceList.setAdapter(deviceListAdapter);
        deviceListAdapter.bindToRecyclerView(rvDeviceList);
        deviceListAdapter.setEmptyView(R.layout.view_empty_list);

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("连接中，请稍等......");
        progressDialog.setCancelable(false);
    }

    @Override
    protected void initListener() {
        super.initListener();
        deviceListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                /*if (defaultSelectDevice != -1)
                    bluetoothDeviceList.get(defaultSelectDevice).setSelect(false);*/
                for (DeviceBean bean : bluetoothDeviceList) {
                    bean.setSelect(false);
                }

                bluetoothDeviceList.get(position).setSelect(true);
                defaultSelectDevice = position;
                selectDeviceBean = bluetoothDeviceList.get(position);
                deviceListAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initResume() {
        super.initResume();
        bluetoothLeUtil.closeBleConnectDevice();
    }

    @OnClick(R.id.btn_search)
    public void onBtnSearchClicked() {
        //如果没有响应权限，则申请权限
        if (bluetoothAdapter.isEnabled()) {
            bluetoothLeUtil.searchBluetoothDevice(bluetoothAdapter, !searchDeviceState);
        } else {
            bluetoothLeUtil.openBluetooth();
        }
    }

    @OnClick(R.id.btn_connect)
    public void onBtnConnectClicked() {
        bluetoothLeUtil.searchBluetoothDevice(bluetoothAdapter, false);

        if (bluetoothLeService == null) {
            ToastUtils.showShort("服务未开启");
        }

        if (bluetoothDeviceList.size() == 0) {
            ToastUtils.showLong("请搜索可用设备");
            return;
        }

        if (selectDeviceBean == null) {
            ToastUtils.showLong("请选择可用设备");
            return;
        }
        bluetoothLeUtil.closeBleConnectDevice();
        bluetoothLeUtil.openBleConnectDevice(bluetoothLeService, selectDeviceBean.getDevice());
        progressDialog.show();

        /*MaterialDialog.Builder materialDialog = new MaterialDialog.Builder(getActivity());
        materialDialog.title("速度校准");
        materialDialog.content("请改变跑步机速度，等待稳定后输入到下栏中");
        materialDialog.inputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
        materialDialog.cancelable(false);
        materialDialog.neutralText("");
        materialDialog.input("请填写速度", null, false, new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                String aa = input.toString();
                float bb = Float.parseFloat(aa);

            }
        });
        materialDialog.show();*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case BluetoothLeParams.Params.INTENT_REQUEST_ENABLE_BLUETOOTH:
                if (resultCode == Activity.RESULT_OK) {
                    bluetoothLeUtil.searchBluetoothDevice(bluetoothAdapter, true);
                } else if (resultCode == Activity.RESULT_CANCELED)
                    bluetoothLeUtil.openBluetooth();
                break;
        }
    }

    /**
     * 判断列表中是否已经存在设备信息
     */
    private boolean isDeviceAlreadyExist(BluetoothDevice device) {
        for (DeviceBean deviceBean : bluetoothDeviceList) {
            if (device.getAddress().equals(deviceBean.getDevice().getAddress()))
                return true;
        }
        return false;
    }


    @Override
    public void onBluetoothUtilCallback(String utilCallbackStatue, BluetoothGatt gatt, BluetoothDevice device, int rssi, byte[] scanRecord, IBinder rawBinder, Intent intent) {
        /*LogUtils.i("UtilCallbackStatue", utilCallbackStatue);*/
        if (progressDialog.isShowing()) progressDialog.dismiss();
        switch (utilCallbackStatue) {
            case BluetoothLeParams.UtilCallbackStatue.STATUS_ServiceConnection_Start:
                btnSearch.setText("Searching......");
                searchDeviceState = true;
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_ServiceConnection_Stop:
                btnSearch.setText("Search");
                searchDeviceState = false;
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_LeScanCallback_Device_Find:
                if (!isDeviceAlreadyExist(device) && (device.getName() != null))
                    deviceListAdapter.addData(new DeviceBean(false, device, rssi, scanRecord));
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_ServiceConnection_ServiceConnected:
                bluetoothLeService = ((BluetoothLeService.LocalBinder) rawBinder).getService(bluetoothLeUtil, bluetoothAdapter);
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_ServiceConnection_ServiceDisconnected:
                ToastUtils.showLong("服务失去连接");
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Connecting:
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Connected:
                Intent intent1 = new Intent();
                intent1.putExtra("DeviceBean", gson.toJson(selectDeviceBean));
                intent1.setClass(getActivity(), EntryActivity.class);
                getActivity().startActivity(intent1);
                break;
            case BluetoothLeParams.UtilCallbackStatue.STATUS_BluetoothDevice_Connect_Fail:
                ToastUtils.showShort("当前设备不能连接");
                break;
        }
    }

    @Override
    protected void initOnDestroy() {
        super.initOnDestroy();
        if (ServiceUtils.isServiceRunning(BluetoothLeService.class)) {
            bluetoothLeService.close();
            bluetoothLeUtil.unBindBluetoothService(getActivity());
        }
    }

    @Override
    public void onBackPressed() {
        BluetoothDialogHelper.showDialog(getActivity(), "提示：", "确定退出应用？", true, new BluetoothDialogHelper.DialogBtnCallback() {
            @Override
            public void dialogBtnCallback(int type) {
                if (type == 1) {
                    if (ServiceUtils.isServiceRunning(BluetoothLeService.class)) {
                        bluetoothLeService.close();
                        bluetoothLeUtil.unBindBluetoothService(getActivity());
                    }
                    AppUtils.exitApp();
                }
            }
        });
    }
}
